# apps/subjects/models.py
from django.db import models
from django.core.exceptions import ValidationError

from apps.tenants.models import Tenant


class Subject(models.Model):
    """
    学科分类表（支持层级结构：一级学科、二级学科）
    对应数据库表: qb_subjects
    """
    name = models.CharField(
        max_length=100,
        verbose_name="学科名称",
        help_text="学科名称，如：数学、语文、英语"
    )
    code = models.CharField(
        max_length=20,
        unique=True,
        null=True,
        blank=True,
        verbose_name="学科编码",
        help_text="学科编码，如：MATH, CHINESE"
    )
    LEVEL_CHOICES = (
        (1, "一级学科"),
        (2, "二级学科"),
    )
    level = models.SmallIntegerField(
        choices=LEVEL_CHOICES,
        default=1,
        verbose_name="学科层级",
        help_text="1: 一级学科, 2: 二级学科"
    )
    parent = models.ForeignKey(
        'self',
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='children',
        verbose_name="父级学科",
        help_text="父级学科ID，自关联"
    )
    is_active = models.BooleanField(
        default=True,
        verbose_name="是否启用"
    )
    sort_order = models.IntegerField(
        default=0,
        verbose_name="排序权重"
    )
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name="创建时间"
    )
    updated_at = models.DateTimeField(
        auto_now=True,
        verbose_name="更新时间"
    )

    tenant = models.ForeignKey(Tenant, on_delete=models.CASCADE, null=True, db_index=True, verbose_name="租户")

    class Meta:
        db_table = 'qb_subjects'
        verbose_name = "学科"
        verbose_name_plural = "学科管理"
        indexes = [
            models.Index(fields=['tenant'], name='idx_subject_tenant'),
            models.Index(fields=['name'], name='idx_name'),
            models.Index(fields=['code'], name='idx_code'),
            models.Index(fields=['parent_id'], name='idx_parent_id'),
        ]

    def __str__(self):
        return self.name

    def get_level_display(self):
        """
        获取层级的中文描述
        """
        return dict(self.LEVEL_CHOICES).get(self.level, "未知层级")

    def is_primary(self):
        """
        判断是否为一级学科
        """
        return self.level == 1

    def is_secondary(self):
        """
        判断是否为二级学科
        """
        return self.level == 2

    def has_children(self):
        """
        判断是否有子学科（二级学科）
        """
        return self.children.exists()

    def clean(self):
        # 1. 自引用校验
        if self.parent == self:
            raise ValidationError('学科不能将自己设为父级。')

        # 2. 二级学科的父级必须是一级学科
        if self.level == 2:
            if not self.parent:
                raise ValidationError('二级学科必须指定父级学科。')
            if self.parent.level != 1:
                raise ValidationError('二级学科的父级必须是一级学科。')
    def save(self, *args, **kwargs):
        self.clean()
        super().save(*args, **kwargs)